<template>
    <CommonModal v-model="state.visible" @handleOk="handleOk" @handleCancel="handleCancel" :title="state.modalTitle">
        <a-form class="form_box" ref="formRef" name="custom-validation" :model="formState" :rules="rules"
            v-bind="layout">
            <a-form-item has-feedback label="用户名" name="nickName" :colon="false">
                <a-input v-model:value="formState.nickName" @change="getTopElevation" autocomplete="off" />
                <!-- <a-input-password v-model:value="formState.userName" :visible="true" :visibility-toggle="false" placeholder="请输入用户名"> -->

                <!-- </a-input-password> -->

            </a-form-item>
            <a-form-item v-if="!formState.id" has-feedback label="密码" name="password" :colon="false">
                <a-input v-model:value="formState.password" autocomplete="off" />
            </a-form-item>

            <a-form-item has-feedback label="人员姓名" name="realName" :colon="false">
                <a-input v-model:value="formState.realName" autocomplete="off" />
                <!-- <a-input-password v-model:value="formState.userName" :visible="true" :visibility-toggle="false" placeholder="请输入用户名"> -->

                <!-- </a-input-password> -->

            </a-form-item>
            <a-form-item has-feedback label="手机号" name="phone" :colon="false">
                <a-input v-model:value="formState.phone" autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="角色" name="roleId" :colon="false">
                <a-select v-model:value="formState.roleId" show-search optionFilterProp="label">
                    <a-select-option :value="item.id" :label="item.name" v-for="(item, index) in state.roleList"
                        :key="index">{{ item.name }}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 20, offset: 0 }" has-feedback label="备注" name="comment" :colon="false">
                <div class="textarea_box">
                    <a-textarea style="height: 100px;" :maxlength="state.maxlength" v-model:value="formState.comment" />
                    <div class="num_box">{{ formState.comment.length }}/{{ state.maxlength }}</div>
                </div>
            </a-form-item>
            <a-form-item label="用户状态" name="isActive" :colon="false">
                <!-- {{ formState.isActive }} -->
                <a-radio-group v-model:value="formState.isActive">
                    <a-radio :value="true">正常</a-radio>
                    <a-radio :value="false">停用</a-radio>
                </a-radio-group>
            </a-form-item>
        </a-form>
        <div class="tips" v-if="!formState.id">密码要求6-16位，包含数字、大小写字母、符号四种元素</div>
    </CommonModal>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import { sysUserAdd, sysUserDetail, sysUserUpdate, sysRoleQueryPage } from '@/service/api'
import { message } from "ant-design-vue";
import { isArray } from "lodash";
const props = defineProps({
    roleList: {
        default: () => [],
        type: Array
    }
})
const emit = defineEmits(['success'])
const formRef = ref()
const state = reactive({
    modalTitle: '',
    visible: false,
    maxlength: 50,
    roleOptions: []
})
// 原始form表单
const defaultFormState = {
    id: '',
    nickName: '', //'绑定的员工',
    realName: '',
    password: 'Zkzh@123',
    isActive: true,
    comment: '',
    roleId:'',
    phone:'',
}
let formState = reactive({
    ...defaultFormState
})
// 验证 禁止输入中文
const getTopElevation = (e) => {
    formState.userName = e.target.value.replace(/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g, '');
}
const validatorTel = async (_rule, value) => {
    const reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if (!value) {
        return Promise.reject("手机号码不能为空");
    } else if (!reg.test(value)) {
        return Promise.reject("手机号码不正确");
    } else {
        return Promise.resolve();
    }
}
const validatePass = async (_rule, password) => {
    if (password === '') {
        return Promise.reject('请输入密码');
    }
    if (password.length < 6 || password.length > 16) {
        return Promise.reject('密码长度必须在6到16位之间');
    }
    // 判断是否包含小写字母
    if (!/[a-z]/.test(password)) {
        return Promise.reject('密码必须包含至少一个小写字母');
    }
    // 判断是否包含大写字母
    if (!/[A-Z]/.test(password)) {
        return Promise.reject('密码必须包含至少一个大写字母');
    }
    // 判断是否包含数字
    if (!/\d/.test(password)) {
        return Promise.reject('密码必须包含至少一个数字');
    }
    // 判断是否包含符号
    if (!/[^\da-zA-Z]/.test(password)) {
        return Promise.reject('密码必须包含至少一个符号');
    }
    return Promise.resolve();
}
const rules = {
    nickName: [{ required: true, trigger: 'change' , message: '请输入用户名'}],
    realName: [{ required: true, trigger: 'change'  , message: '请输入姓名'}],
    password: [{ required: true, trigger: 'change', validator: validatePass }],
    roleId: [{ required: true, trigger: 'change', message: '请选择角色' }],
    phone: [{ required: true, trigger: 'blur'  ,  validator:validatorTel}],
};
const layout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 12,
    },
};
onMounted(() => {
    getRolePage()
    // let params = {
    //     key: 'com.ggzn.sysmgr.emp', 
    //     json:JSON.stringify({
    //     })
    // }
    // udmData(params).then(res=>{
    //     if(res && res.status ==='000_0000_0000') {
    //         state.roleOptions = res.data.result;
    //     }
    // })
})

// 确认
const handleOk = () => {
    formRef.value.validateFields().then(r => {
        console.log(3333, r)
        let params = {
            ...formState,
        }

        let axios = formState.id ? sysUserUpdate : sysUserAdd;
        axios(params).then(res => {
            if (res.status == "000_0000_0000") {
                message.success('添加成功');
                handleCancel()
                emit('success')
            } else {
                message.error(res.messages)
            }
        })
        // // 新增用户
        // if(!formState.id) {

        //     logicflowSync({
        //         chainId: 'com.ggzn.sysmgr.user.add',
        //         json: JSON.stringify(params)
        //     }).then(res => {
        //         if (res.status == "000_0000_0000") {
        //             message.success('添加成功');
        //             handleCancel()
        //             emit('success')
        //         }
        //     })
        // }else{
        //     delete params.user_password;
        //     logicflowSync({
        //         chainId: 'com.ggzn.sysmgr.user.edit',
        //         json: JSON.stringify(params)
        //     }).then(res => {
        //         if (res.status == "000_0000_0000") {
        //             message.success('修改成功');
        //             handleCancel()
        //             emit('success')
        //         }
        //     })
        // }

    }).catch(err=>{
        message.error('字段验证不通过')
    })
}
// 取消
const handleCancel = () => {
    formRef.value.resetFields()
    state.visible = false
    formState = reactive({ ...defaultFormState })
}
const showModal = (obj) => {
    state.modalTitle = obj.title;
    state.visible = true
    // console.log(obj,'formState--obj');
    if (obj.id) {
        Object.keys(formState).forEach(item => {
            formState[item] = obj[item]
        })
        // console.log(formState,'formState');
        // formState.roleId = obj.role_id ? obj.role_id.split(',') : [];
        // // console.log(obj,99999,formState.roleId);
        // if (!obj.emp_name) {
        //     // formState.emp_id = null
        // } else {
        //     state.roleOptions = [{ emp_name: obj.emp_name, id: obj.emp_id }]
        // }
    }

}
//获取列表数据
const getRolePage = () => {
    let params = {
        likeName: '',
        pageNum: 1,
        pageSize: 999,
    }
    sysRoleQueryPage(params).then(res => {
        if (res.result) {
            state.roleList = res.result.list;

        }
    })

}
defineExpose({ showModal })
</script>
<style scoped lang="less">
.form_box {

    input,
    :deep(.JManage-select-selector) {
        width: 200px;
        min-height: 32px;
        box-sizing: border-box;
        background: #FFFFFF;
        border-radius: 6px;
        border: 1px solid #E0E0E0;
    }

    :deep(.JManage-select-show-arrow) {
        width: 200px;
    }

    .JManage-radio-group {
        width: 250px;
    }

    :deep(.JManage-form-item-control-input .JManage-form-item-control-input-content) {
        width: 100%;
    }

    textarea {
        height: 64px;
        border-radius: 6px;
        border: 1px solid #E0E0E0;
    }

    .textarea_box {
        position: relative;

        .num_box {
            position: absolute;
            bottom: 8px;
            right: 8px;
            color: #999999;
        }
    }
}

.tips {
    width: 392px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    margin: 24px auto 0;
    font-size: 14px;
    background: #F5F5F5;
    color: #999999;
    border-radius: 4px;
}
</style>
